package com.atguign.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.shaded.io.grpc.internal.JsonUtil;
import com.atguign.gulimall.product.service.CategoryBrandRelationService;
import com.atguign.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguign.gulimall.product.dao.CategoryDao;
import com.atguign.gulimall.product.entity.CategoryEntity;
import com.atguign.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //level1
        return categoryEntities.stream().filter((item) -> item.getCatLevel() == 1)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, categoryEntities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO 检查引用
        baseMapper.deleteBatchIds(list);
    }

    /**
     * 找到Catelog的路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        return paths;
    }

    /**
     * 级联更新所有数据
     *
     * @param category
     */

    @Transactional
    @Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'"),
            @CacheEvict(value = {"category"}, key = "'getCatalogJson'")
    })
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.hasText(category.getName()))
            categoryBrandRelationService.updateCascade(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getCatLevel, 1));
    }

    /**
     * 首页商品类目
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        Map<String, List<Catalog2Vo>> collect1 = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString()
                , v -> {
                    List<CategoryEntity> parentCid = this.getParent_cid(categoryEntities, v.getCatId());
                    return parentCid.stream().map(item -> {
                        Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), item.getCatId().toString(), item.getName(), null);
                        List<CategoryEntity> parentCid1 = this.getParent_cid(categoryEntities, item.getCatId());
                        List<Catalog2Vo.Catalog3List> collect = parentCid1.stream().map(parentCid3 -> new Catalog2Vo.Catalog3List(
                                        item.getCatId().toString(),
                                        parentCid3.getCatId().toString(),
                                        parentCid3.getName()))
                                .collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                        return catalog2Vo;
                    }).collect(Collectors.toList());
                })
        );
        return collect1;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String json = ops.get("catalogJsonByDB");
        if (!StringUtils.hasText(json)) {

            return getCatalogJsonByDBRedisson();
        }
        return JSON.parseObject(json, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });

    }

    /**
     * Redisson锁
     *
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonByDBRedisson() {
        RLock catalogJson = redisson.getLock("CatalogJson");
        catalogJson.lock();
        Map<String, List<Catalog2Vo>> stringListMap;
        try {
            stringListMap = getStringListMap();
        } finally {
            catalogJson.unlock();
        }
        return stringListMap;
    }

    /**
     * redis锁
     *
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonByDBRedis() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String uuid = UUID.randomUUID().toString();
        Boolean lock = ops.setIfAbsent("lock", uuid, 300, TimeUnit.MINUTES);
        if (Boolean.TRUE.equals(lock)) {
            Map<String, List<Catalog2Vo>> stringListMap;
            try {
                stringListMap = getStringListMap();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList("lock"), uuid);
            }
            return stringListMap;
        } else {

            return getCatalogJsonByDBRedis();
        }
    }

    /**
     * 本地锁
     *
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonByDB() {
        synchronized (this) {
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            return getStringListMap();
        }

    }

    private Map<String, List<Catalog2Vo>> getStringListMap() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String json = ops.get("catalogJsonByDB");
        if (StringUtils.hasText(json)) {
            return JSON.parseObject(json, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        System.out.println("搜索DB");
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        Map<String, List<Catalog2Vo>> collect1 = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString()
                , v -> {
                    List<CategoryEntity> parentCid = this.getParent_cid(categoryEntities, v.getCatId());
                    return parentCid.stream().map(item -> {
                        Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), item.getCatId().toString(), item.getName(), null);
                        List<CategoryEntity> parentCid1 = this.getParent_cid(categoryEntities, item.getCatId());
                        List<Catalog2Vo.Catalog3List> collect = parentCid1.stream().map(parentCid3 -> new Catalog2Vo.Catalog3List(
                                        item.getCatId().toString(),
                                        parentCid3.getCatId().toString(),
                                        parentCid3.getName()))
                                .collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                        return catalog2Vo;
                    }).collect(Collectors.toList());
                })
        );
        ops.set("catalogJsonByDB", JSON.toJSONString(collect1), 1, TimeUnit.DAYS);
        return collect1;
    }


    private void findParentPath(Long catelogId, ArrayList<Long> paths) {
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        paths.add(catelogId);
    }


    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter((item) -> Objects.equals(item.getParentCid(), root.getCatId()) && item.getCatLevel() == root.getCatLevel() + 1)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, all));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    public List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long parent_cid) {
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == parent_cid).collect(Collectors.toList());
    }
}